﻿using System;
using System.Diagnostics;
using System.Reflection;

namespace Ooaavee.Scripting.Remoting
{
    /// <summary>
    /// Base class for scripts.
    /// </summary>
    [Serializable]
    public abstract class RemoteScript : MarshalByRefObject, IRemoteScript
    {        
        /// <summary>
        /// Gets the script parameters.
        /// </summary>
        protected virtual RemoteScriptParameters Parameters { set; get; }

        [DebuggerStepThrough]
        object IRemoteScript.Invoke(string method, RemoteScriptParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Parameters = parameters;

            InitializeScript();

            Type type = GetType();

            object returnValue = type.InvokeMember(method,
                                                   BindingFlags.InvokeMethod,
                                                   null,
                                                   this,
                                                   new object[] {});

            return returnValue;
        }

        /// <summary>
        /// Occurs when a script should be initialized.
        /// </summary>
        protected virtual void InitializeScript()
        {            
        }
    }
}